Ext.namespace('Mia.util');
Ext.BLANK_IMAGE_URL = '/my/commons/ext/resources/images/default/s.gif';
var AppCfg = {
	base : "/webapp",
	treeUrl :"/webapp/widgets/getTree.do?code={0}",
	comboUrl :"/webapp/widgets/getCombo.do?code={0}",
	errorMsg : "操作失败!可能session失效,请重新登陆!",
	validMsg : '请输入完整或合法的数据',
	confirmMsg : '你确认要提交吗?',
	okMsg : '操作成功',
	error : '操作失败',
	hit : '系统提示',
	tb : {
		add : '新增',
		edit : '修改',
		del : '删除',
		query:'查询',
		save:'保存'
	}
};
var MiaUtil = {
	getTreePanel : function(config) {
		var dataUrl=config.url||String.format(AppCfg.treeUrl,config.code);
		var loader=new Ext.tree.TreeLoader({dataUrl:dataUrl,baseParams:config.baseParams||{}});
		var rootCfg={id:config.rootId,text:config.rootText,expanded : true};
		delete config.rootId,config.rootText,config.code,config.url;
		var root =new Ext.tree.AsyncTreeNode(rootCfg);
		config=Ext.applyIf(config,{split : true,autoScroll : true,animCollapse : false,collapsible : true,collapseMode : 'mini',singleExpand : true,frame : false,width:100,maxSize : 500,loader : loader,root : root});
		return new Ext.tree.TreePanel(config);
	},
	/**
	 * cofig:自定义参数
	 * 		cols:列模型
	 * 		rType:记录类型,如果为空则从colModel取
	 * 		singleSelect:是否单选
	 * 其他参数参考Ext的GridPanel的API
	 */
	getGridPanel : function(config) {
		var cols = config.cols;
		delete config.cols;
		var nCm = [];
		Ext.each(cols,function(e){
			if(e.constructor=== Array){
				var cfg = {header : e[0],dataIndex : e[1]};
				var tmp=e[2];
				if(typeof(tmp)=='object'){
					if(!tmp.editor){
						if(tmp.xtype){
							tmp.editorConfig={xtype:tmp.xtype};
							delete tmp.xtype;
						}
						if(tmp.editorConfig){
							var xtype=tmp.editorConfig.xtype;
							if(xtype=='datefield'){
								if(!tmp.editorConfig.format){
									tmp.editorConfig.format='Y-m-d';
								}
								if(!tmp.renderer){
									tmp.renderer=Mia.util.Format.dateRenderer('Y-m-d');
								}
							}
							tmp.editor=Ext.ComponentMgr.create(tmp.editorConfig,'textfield');
						}
					}
					Ext.apply(cfg, tmp);
				}
				nCm.push(cfg);
			}else{
				nCm.push(e);
			}
		});
		
		//设置数据源
		if (!config.ds) {
			var recrodType = [];
			if(config.rType){ 
				recrodType=rType
				delete config.rType;
			}else{
				Ext.each(nCm,function(e){
					recrodType.push(e.dataIndex);
				});
			}
			config.ds = this.getStore(recrodType,config);
		}
		//设置checkbox列
		var tmp=[new Ext.grid.RowNumberer()];
		if(config.checkbox!==false){
			var sm = new Ext.grid.CheckboxSelectionModel({
				singleSelect : config.singleSelect|| false
			});
			config.sm = sm;
			tmp.push(sm);
		}
		tmp=tmp.concat(nCm);
		var cm = new Ext.grid.ColumnModel(tmp);
		config.cm = cm;
		config.cm.defaultSortable = true;
		delete config.singleSelect;
		//设置topBar
		var tbar=config.tbar;
		if(tbar&&tbar.constructor===Object){
			var tbs = [], i = 0;
			for (var t in tbar) {
				if (i++ != 0)
					tbs.push("-");
				var tb = {
					text : AppCfg.tb[t],
					iconCls : t,
					handler : tbar[t]
				};
				tbs.push(tb);
			}
			config.tbar=tbs;
		}
		//设置buttomBar
		config.bbar=config.bbar||this.getPagingToolbar(config.ds, config.excel);
		return new Ext.grid.EditorGridPanel(config);
	},
	getStore : function(cm, opt) {
		opt=opt||{};
		var reader;
		if(opt.type=='xml'){
			var meta = {record: 'data', totalRecords: 'state', success: '@success'};	
			reader=new Ext.data.XmlReader(meta, cm);
		}else{
			var meta= {totalProperty : "total",root : "rows"};
			reader=new Ext.data.JsonReader(meta, cm);
		}
		return new Ext.data.Store({
			proxy:new Ext.data.HttpProxy( {'url' : opt.url||''}),
			reader:reader,remoteSort: opt.remoteSort!==false});
	},
	getPagingToolbar : function(ds, fn, pageSize) {
		var bbar = [{
			iconCls : 'x-xls-icon',
			tooltip : '导出到Excel',
			handler : fn
		}];
		var s = pageSize || 20;
		return new Ext.PagingToolbar({
			//plugins : [new Ext.ux.grid.PageSize()],
			pageSize : s,
			store : ds,
			items : bbar,
			displayInfo : true,
			displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条', 
			emptyMsg : "没有记录"
		});
	},
	getFormItem : function(text, name, extra, prefix) {
		if (prefix)
			name = prefix + "." + name;
		extra = extra || {};
		var elt = [];
		var xtype = extra.xtype || 'textfield';
		var ctl = {
			xtype : xtype,
			id : name,
			name : name,
			fieldLabel : text
		};
		switch (xtype) {
			case 'textfield' :
				break;
			case 'combo' :
				Ext.applyIf(ctl, {
					width : 130,
					valueField : "ID",
					displayField : "TEXT",
					editable : false,
					triggerAction : 'all',
					forceSelection : true
				});
				var url=extra.url||String.format(AppCfg.comboUrl, extra.code);
				ctl.store = new Ext.data.JsonStore({
					autoLoad : true,
					root : 'rows',
					url : url,
					id : 'ID',
					fields : ['ID', 'TEXT']
				});
				break;
			case 'datefield' :
				ctl.format = extra.format || 'Y-m-d';
				ctl.width = 130;
				break;
			case 'searchfield' :
				break;
			case 'hidden' :
				elt.remove(0);
				break;
		}
		if (extra.colspan) {
			ctl.width = extra.width || '90%';
		}
		Ext.apply(ctl, extra || {});
		if (prefix && ctl.hiddenName) {
			ctl.hiddenName = prefix + "." + ctl.hiddenName;
		}
		elt.push(ctl);
		return elt;
	},
	getFormItems : function(array, prefix) {
		var elts = [];
		for (var i = 0; i < array.length; i++) {
			elts = elts.concat(this.getFormItem(array[i][0], array[i][1],
					array[i][2], prefix));
		}
		return elts;
	},
	getFormPanel : function(param) {
		var items = param.fields || [];
		param.items = this.getFormItems(items, param.prefix);
		var reader = null;
		if (param.hasReader !== false) {
			var c = [];
			if (param.prefix) {
				for (var i = 0; i < items.length; i++) {
					if (items[i].constructor === Object) {
						c.push(items[i]);
					} else {
						c.push({
							name : param.prefix + '.' + items[i][1],
							mapping : items[i][1]
						});
						var tt = items[i][2] || {};
						if (tt.hiddenName) {
							c.push({
								name : param.prefix + '.' + tt.hiddenName,
								mapping : tt.hiddenName
							});
						}
					}
				}
			} else {
				for (var i = 0; i < items.length; i++) {
					c.push(items[i][1]);
				}
			}
			reader = new Ext.data.JsonReader({
				root : 'rows'
			}, c);
		}
		var layout = param.layout ? param.layout : (param.layoutConfig
				? 'formtable'
				: 'form');
		Ext.applyIf(param, {
			frame : true,
			reader : reader,
			layout : layout
		});
		param.fields=null;
		param.actions=null;
		delete param.id;
		return new Ext.FormPanel(param);
	},
	getColValue : function(records, col, pre) {
		col = col || "ID";
		pre = pre || "lst";
		var v = [];
		for (var i = 0; i < records.length; i++) {
			v.push(pre + "=" + records[i].get(col));
		}
		return v.join("&");
	},
	getCombo : function(param, extParam) {
		extParam = extParam || {};
		var fields = param.fields || ['ID', 'TEXT'];
		var cfg = {
			xtype : 'combo',
			valueField : fields[0],
			displayField : fields[1],
			editable : false,
			triggerAction : 'all',
			forceSelection : true,
			store : new Ext.data.JsonStore({
				root : 'rows',
				url : param.url,
				id : fields[0],
				fields : fields
			})
		};
		Ext.apply(cfg, extParam);
		return new Ext.form.ComboBox(cfg);
	},
	getQueryPage:function(param, extParam){
		extParam = extParam || {};
		var cfg={
			tbar:[{
				text:'增加',handler:function(){
						Query.add();
					 },scope:this},{
				text:'查询',handler:function(){
					param.ds.reload({params:{_query:Query.param()}});
				}
			}],
			fields:param.fields
		}
		Ext.apply(cfg, extParam);
		return new Ext.ux.QueryPage(cfg);
	},
	load : function(ds, url, opt) {
		var params = {
			start : 0,
			url : url
		};
		Ext.apply(ds.proxy.conn, {
			url : params.url,
			success : function(response, options) {
				// var rst=Ext.util.JSON.decode(response.responseText);
				// if(rst.success===false){
				// 处理错误
				// }
			}
		});
		Ext.apply(params, opt || {});
		ds.reload({
			params : params
		});
	},
	submit : function(frmPanel, url, fn) {
		Ext.Msg.confirm("系统提示", "您确定要提交吗?", function(btn) {
			if (btn == "yes") {
				frmPanel.form.submit({
					url : url,
					success : function(form, action) {
						if (fn)
							fn();
						Ext.Msg.alert("操作成功!");
					},
					failure : function(form, action) {
						Ext.Msg.alert("操作失败!");
					},
					clientValidation : true
				});
			}
		});
	},
	showPage : function(title, page, opt) {
		page.setTitle(title);
		opt = opt || {};
		var url = opt.url;
		if (url) {
			var sm = opt.grid ? grid.getSelectionModel() : opt.sm;
			var records = sm.getSelections();
			if (records.length != 1) {
				Ext.Msg.alert("系统提示", "请选择一项您要修改的记录!");
				return;
			} else {
				var params = opt.params;
				if (typeof(params) == 'string') {
					params = [params];
				}
				var str = [];
				for (var i = 0; i < params.length; i++) {
					str.push(params[i] + "=" + records[0].get(params[i]))
				}
				page.show();
				page.form.load({
					url : url,
					params : str.join("&") || "",
					waitMsg : "载入..."
				});
			}
		} else {
			page.show(this);
		}
	},
	del : function(url, grid, params, opt) {
		var opt = opt || {};
		var sm = grid.getSelectionModel();
		var records = sm.getSelections();
		if (records.length == 0) {
			Ext.Msg.alert("系统提示", "请选择您要删除的记录!");
			return;
		} else {
			var params = params || ["ID"];
			if (typeof(params) == 'string') {
				params = [params];
			}
			var str = [];
			if (records.length > 0) {
				for (var i = 0; i < records.length; i++) {
					for (var j = 0; j < params.length; j++) {
						str.push(params[j] + "=" + records[i].get(params[j]))
					}
				}
			}
			var fn;
			if (opt.reload) {
				fn = function() {
					grid.getStore().reload();
				}
			}
			AjaxUtil.request(url, str.join("&"), fn);
		}
	},
	serializeForm:function(form,asString){
		var fs = Ext.lib.Ajax.serializeForm(form);
	    if(asString === true){
	        return fs;
	    }
	    return Ext.urlDecode(fs);
	},
	serialize:function(){
		var pair={};
		Ext.each(arguments,function(e){
			var c=Ext.getDom(e);
			pair[c.name||c.id]=c.value;
		});
	    return Ext.urlDecode(pair);
	},
	toXml:function(ds,cols){
		var data=[];
		if(cols){
			ds.each(function(rec){
				if (rec.newflag || rec.dirty){
					data.push("<data><action>",(rec.newflag?'i':'u'),"</action>");
					Ext.each(cols,function(col){
						data.push("<",col,"><![CDATA[",rec.data[col],"]]></",col,">");
					})
					data.push("</data>");
				}
			})
		}else{
			ds.each(function(rec){
				if (rec.newflag || rec.dirty){
					data.push("<data><action>",(rec.newflag?'i':'u'),"</action>");
					for(var col in rec.data){
						data.push("<",col,"><![CDATA[",rec.data[col],"]]></",col,">");
					}
					data.push("</data>");
				}
			})
		}
		return data.join("");
	}
}

var AjaxUtil = {
	request : function(url, params, fn, fail) {
		if (typeof(params) == 'function') {
			fn = params;
			params = null;
		}
		Ext.Ajax.request({
			url : url,
			success : function(response, options) {
				var rst = Ext.util.JSON.decode(response.responseText);
				if (rst.success === true) {
					if (fn)
						fn();
					Ext.Msg.alert(AppCfg.hit, AppCfg.okMsg);
				}
			},
			failure : function(response, options) {
				Ext.Msg.alert(AppCfg.hit, AppCfg.error);
			},
			params : params
		});
	}
};

Mia.util.Format={
	dateRenderer : function(format){
		
		    return function(v){
		        return Mia.util.Format.date(v, format);
	    };
	},
   date : function(v, format){
        if(!v){
            return "";
        }
        if(!Ext.isDate(v)){
            v = new Date(Date.parse(v.replace(/-/g,'/')));
        }
        return v.dateFormat(format || "Y-m-d");
    }
}